package com.example.chatgpt.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.chatgpt.R;
import com.example.chatgpt.bean.Message;
import com.example.chatgpt.util.TimeUtil;

import org.w3c.dom.Text;

import java.sql.Time;
import java.util.List;

public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MyViewHolder> {

    List<Message> messageList;

    public MessageAdapter(List<Message> messageList) {
        this.messageList = messageList;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_message, null);
        MyViewHolder holder = new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        String message = messageList.get(position).getMessage();
        String sentBy = messageList.get(position).getSentBy();
        if (sentBy.equals(Message.SENT_BY_ROBOT)) {
            //如果正在请求中则不显示时间 返回结果显示在屏幕上时才显示时间
            if (messageList.get(position).message.equals("正在请求 骚等~")) {
                holder.rl_me.setVisibility(View.GONE);
                holder.rl_robot.setVisibility(View.VISIBLE);
                holder.tv_robot.setText(message);
                holder.tv_date.setVisibility(View.GONE);
            } else {
                holder.rl_me.setVisibility(View.GONE);
                holder.rl_robot.setVisibility(View.VISIBLE);
                holder.tv_robot.setText(message);
                holder.tv_date.setVisibility(View.VISIBLE);
                holder.tv_date.setText(TimeUtil.getTimeNow());
            }
        } else {
            holder.rl_robot.setVisibility(View.GONE);
            holder.rl_me.setVisibility(View.VISIBLE);
            holder.tv_me.setText(message);
            holder.tv_date.setText(TimeUtil.getTimeNow());
        }
    }

    @Override
    public int getItemCount() {
        return messageList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        RelativeLayout rl_robot;
        RelativeLayout rl_me;
        TextView tv_robot;
        TextView tv_me;
        TextView tv_date;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            rl_robot = itemView.findViewById(R.id.rl_robot);
            rl_me = itemView.findViewById(R.id.rl_me);
            tv_robot = itemView.findViewById(R.id.tv_robot);
            tv_me = itemView.findViewById(R.id.tv_me);
            tv_date = itemView.findViewById(R.id.tv_date);
        }
    }
}
